package com.tyros.common.aspect;

import com.alibaba.fastjson.JSON;
import com.tyros.common.utils.HttpContextUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author zhangshuaiyin
 * @date 2022-1-15 21:04:17
 */
@Slf4j
@Aspect
@Component
public class ApiOperationAspect {

    @Around("@annotation(apiOperation)")
    public Object doAround(ProceedingJoinPoint joinPoint, ApiOperation apiOperation) throws Throwable {
        long startTime = System.currentTimeMillis();
        // 执行切点方法
        Object result = joinPoint.proceed();
        HttpServletRequest request = HttpContextUtils.getRequest();
        assert request != null;
        String content = "";
        content += "\n========================== Request Info ==========================";
        content += "\nExecute Method : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName() + "()";
        content += "\nRequest API    : " + request.getRequestURI();
        content += "\nHTTP Method    : " + request.getMethod();
        content += "\nAPI Description: " + apiOperation.value();
        content += "\nRequest Params : " + JSON.toJSONString(joinPoint.getArgs());
        content += "\nIP Address     : " + request.getRemoteAddr();
        content += "\nReturn Result  : " + result;
        content += "\nTotal Mills    : " + (System.currentTimeMillis() - startTime) + "ms";
        content += "\n========================== Request  END ==========================";
        log.info(content);
        return result;
    }

    @AfterThrowing(throwing = "ex", pointcut = "@annotation(apiOperation)")
    public Object throwing(ApiOperation apiOperation, Throwable ex) {
        HttpServletRequest request = HttpContextUtils.getRequest();
        assert request != null;
        String content = "";
        content += "\n========================== Request Error Info ==========================";
        content += "\nRequest API    : " + request.getRequestURI();
        content += "\nHTTP Method    : " + request.getMethod();
        content += "\nAPI Description: " + apiOperation.value();
        content += "\nIP Address     : " + request.getRemoteAddr();
        content += "\nThrowable      : " + ex;
        content += "\n========================== Request  END ==========================";
        log.error(content);
        return null;
    }
}
